// pages/home/home.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo: undefined,
  },
  getUserId(){
    const user = wx.getStorageSync('user')
    console.log(user.username)
    wx.request({
      url: `http://localhost:8089/user/searchByUserName/${user.username}`,
      data: user.username,
      header: {
        'content-type': 'application/json'
      },
      method: 'GET',
      dataType: "json",
      success: (res)=>{
        console.log(res.data) 
        wx.setStorageSync('userId', res.data.data.userId)
      },
    })
  },
  gotoOrder(){
    this.getUserId()
    wx.navigateTo({
      url: '/pages/order/order',
    })
  },
  gotoCart(){
    this.getUserId()
    wx.switchTab({
      url: '/pages/shopcart/shopcart',
    })
  },
  loginWx(){
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        const code = res.code;
        // 设置appid
        const appId = "wxe8ef20f4afc61aac";
        // const appid = res.appid;
        //设置secret
        const secret = "842abd969e65aa3b6d07dae878ed5f75";
        wx.request({
          url: 'https://api.weixin.qq.com/sns/jscode2session?appid=' + appId + '&secret=' + secret + '&js_code=' + code + '&grant_type=authorization_code',
          data: {},
          header: {
            'content-type': 'json'
          },
          success: function (res) {         
            const openId = res.data.openid; //返回openid
            console.log(".........")
            console.log(openId)
            function person(username,password){
              this.username = username;
              this.password = password;
            }
            var user = new person(openId,openId)        
            wx.setStorageSync('user', user)
          }
        })
      }
    })
  },
  getUser() {
    wx.clearStorage()
    this.loginWx()
    console.log(wx.getStorageSync('user'))
    wx.getUserProfile({
      desc: "获取用户头像昵称",
      success: (res) => {
        // console.log(res.userInfo)
        this.setData({
          userInfo: res.userInfo,
        });
      },
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})